import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

url = "https://www.baidu.com"

brower = webdriver.Chrome(executable_path='chromedriver')




# 等待元素加载
def wait_element(brower, element_id, wait_time=10):
    try:
        # 隐式等待
        # brower：需要隐式等待的浏览器
        # wait_time：最长等待实际
        # 1：每隔1秒判断一下对应的元素是否成功加载
        WebDriverWait(brower, wait_time, 1).until(
            EC.presence_of_element_located((By.ID, element_id))
        )
    except Exception as e:
        # 元素等待了 wait_time 时间，已经没有完成加载
        raise Exception(e)

try:
    brower.get(url)
    # 找到网页中 id 为 kw 的元素 -> 百度搜索输入框
    input = brower.find_element_by_id('kw')
    # 清空输入框
    input.clear()
    # 输入Python
    input.send_keys("Python")
    # 敲击回车键
    input.send_keys(Keys.ENTER)
    # 等待元素加载
    wait_element(brower, 'content_left')
    print(brower.current_url)
    print(brower.get_cookies())
    print(brower.page_source)
finally:
    time.sleep(5)
    # 退出浏览器
    brower.close()
